package com.dtwave.wechat.service.provider.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.dtwave.wechat.service.provider.core.wx.WechatRequest;
import com.dtwave.wechat.service.provider.core.wx.WeiXinMakeToken;
import com.dtwave.wechat.service.provider.core.wx.WeiXinMethodUtil;
import com.dtwave.wechat.service.provider.core.wx.WeiXinProperties;
import com.dtwave.wechat.service.provider.database.dao.NotifyMapper;
import com.dtwave.wechat.service.provider.database.entity.BasNotifyEntity;
import com.dtwave.wechat.service.provider.database.entity.BasNotifySendeeEntity;
import com.dtwave.wechat.service.provider.database.entity.UserEntity;
import com.dtwave.wechat.service.provider.dto.NotifyDto;
import com.dtwave.wechat.service.provider.service.INotifySendeeService;
import com.dtwave.wechat.service.provider.service.INotifyService;
import com.dtwave.wechat.service.provider.service.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Auther: liuwenxiang
 * @Date: 2019/2/26 11:29
 * @Description:
 */

@Service
public class NotifyServiceImpl extends ServiceImpl<NotifyMapper,BasNotifyEntity> implements INotifyService {

    private static Logger logger = LoggerFactory.getLogger(NotifyServiceImpl.class);

    @Autowired
    private NotifyMapper notifyMapper;

    @Autowired
    WeiXinProperties weiXinProperties;

    @Autowired
    UserService userService;

    @Autowired
    private INotifySendeeService iNotifySendeeService;

    @Value("${ht.address}")
    private  String address;

    @Override
    public List<Map<String, Object>> getNotifyList(String userId, String type) {
        return notifyMapper.getNotifyList(userId, type);
    }

    @Override
    public List<Map<String, Object>> getReceiveNotifyList(String userId, String type) {
        return notifyMapper.getReceiveNotifyList(userId, type);
    }

    @Override
    public boolean setReadFlag(Integer notifyId, String userId) {
        String readFlag = notifyMapper.getReadFlag(notifyId, userId);
        if (StringUtils.isEmpty(readFlag) || ("0").equals(readFlag)) {//未读
            notifyMapper.setReadFlag(notifyId, userId);//设置为已读
        }
        return true;
    }


    @Override
    public List<Map<String, Object>> getReceiverList(Integer notifyId) {
        return notifyMapper.getReceiverList(notifyId);
    }


    @Override
    public Map<String, Object> notifyDetail(Integer notifyId) {
        return notifyMapper.notifyDetail(notifyId);
    }


    @Override
    public boolean notifyCheck(Integer notifyId, String userId) {
        return notifyMapper.notifyCheck(notifyId, userId);
    }


    @Override
    @Transactional
    public boolean notifyPublish(NotifyDto notifyDto) {
        String status = notifyDto.getStatus();
        Integer notifyId = notifyDto.getNotifyId();
        BasNotifyEntity be = null;
        if (notifyId != null && notifyId > 0) {//修改
            be = selectById(notifyDto.getNotifyId());
            be.setTitle(notifyDto.getTitle());
            be.setContent(notifyDto.getContent());
            be.setFiles(notifyDto.getFiles());
            be.setStatus(status);
            be.setCUserId(notifyDto.getUserId());
            updateById(be);//更新通知通报

            Wrapper<BasNotifySendeeEntity> wrapperDel = new EntityWrapper<BasNotifySendeeEntity>();
            wrapperDel.eq("notify_id", notifyId);
            iNotifySendeeService.delete(wrapperDel);//删除原来的接受人列表
        } else {//新增
            be = new BasNotifyEntity();
            be.setTitle(notifyDto.getTitle());
            be.setContent(notifyDto.getContent());
            be.setFiles(notifyDto.getFiles());
            be.setStatus(status);
            be.setCUserId(notifyDto.getUserId());
            insert(be);//新增通知通报
        }

        List<String> bnsList = notifyDto.getReceiveList();
        if(CollectionUtils.isNotEmpty(bnsList)){
            WechatRequest re = new WechatRequest();
            re.setRequestId("1");
            re.setCorpId(weiXinProperties.getCropid());
            re.setSecret(weiXinProperties.getAppsecret_tztb());
            re.setAgentid(weiXinProperties.getAppid_tztb());
            re.setTitle(be.getTitle());
            String photo ="http://pic.baike.soso.com/p/20131220/20131220121215-1470431134.jpg";
            String files = StringUtils.isNotEmpty(notifyDto.getFiles())?"http://"+address+":8080/"+notifyDto.getFiles().split(",")[0]:photo;
            re.setPicurl(files);
            re.setMsgType("news");
            logger.info("*************************推送消息图片地址："+files);
            for (String receiveUserId : bnsList) {
                BasNotifySendeeEntity bns = new BasNotifySendeeEntity();
                bns.setNotifyId(be.getId());
                bns.setReceiveUserId(receiveUserId);
                iNotifySendeeService.insert(bns);
                if (("1").equals(status)) {//发布
                    re.setTouser(receiveUserId);
                    re.setDescription(notifyDto.getContent());
                    re.setToparty("");
                    re.setUrl("http://"+address+"/pages/receive-detail/receive-detail?userId="+notifyDto.getUserId()+"&keyId="+be.getId());
                    WeiXinMethodUtil.Send_msg(re, "news", WeiXinMakeToken.accessToken_tztb.getToken());
                }
            }
        }
        return true;
    }

    @Override
    public  String uploadFile() {


        return null;
    }







}